import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 读取food_data.json
const foodDataPath = path.join(__dirname, '../database/food_data.json')
let foodData
try {
  const rawData = fs.readFileSync(foodDataPath, 'utf8')
  foodData = JSON.parse(rawData)
} catch (error) {
  console.error('Error reading food_data.json:', error)
  process.exit(1)
}

console.log(`读取到 ${foodData.length} 个食物条目`)

// 筛选有基本数据的食物（至少有名称和基本营养信息）
const validFoods = foodData.filter(food => 
  food.name_zh && 
  food.name_en && 
  typeof food.protein_g === 'number' && 
  typeof food.fat_g === 'number' && 
  typeof food.carb_g === 'number'
)

console.log(`找到 ${validFoods.length} 个有效食物`)

// 转换为完整的Food类型格式，补充缺失的字段 - 使用所有有效食物
const convertedFoods = validFoods.map(food => ({
  id: food.id,
  name_zh: food.name_zh,
  name_en: food.name_en,
  energy_kcal: food.energy_kcal || 0,
  energy_rich: food.energy_rich || false,
  protein_g: food.protein_g || 0,
  protein_rich: food.protein_rich || false,
  fat_g: food.fat_g || 0,
  fat_rich: food.fat_rich || false,
  carb_g: food.carb_g || 0,
  carb_rich: food.carb_rich || false,
  fiber_g: food.fiber_g || 0,
  fiber_rich: food.fiber_rich || false,
  cholesterol_mg: food.cholesterol_mg || 0,
  cholesterol_rich: food.cholesterol_rich || false,
  sodium_mg: food.sodium_mg || 0,
  sodium_rich: food.sodium_rich || false,
  calcium_mg: food.calcium_mg || 0,
  calcium_rich: food.calcium_rich || false,
  phosphorus_mg: food.phosphorus_mg || 0,
  phosphorus_rich: food.phosphorus_rich || false,
  potassium_mg: food.potassium_mg || 0,
  potassium_rich: food.potassium_rich || false,
  iron_mg: food.iron_mg || 0,
  iron_rich: food.iron_rich || false,
  // 补充缺失的维生素字段，使用默认值
  vitamin_a_ug: food.vitamin_a_ug || 0,
  vitamin_a_rich: food.vitamin_a_rich || false,
  vitamin_c_mg: food.vitamin_c_mg || 0,
  vitamin_c_rich: food.vitamin_c_rich || false,
  vitamin_d_mcg: food.vitamin_d_mcg || 0,
  vitamin_d_rich: food.vitamin_d_rich || false,
  vitamin_e_mg: food.vitamin_e_mg || 0,
  vitamin_e_rich: food.vitamin_e_rich || false,
  thiamin_mg: food.thiamin_mg || 0,
  thiamin_rich: food.thiamin_rich || false,
  riboflavin_mg: food.riboflavin_mg || 0,
  riboflavin_rich: food.riboflavin_rich || false,
  vitamin_b6_mg: food.vitamin_b6_mg || 0,
  vitamin_b6_rich: food.vitamin_b6_rich || false,
  vitamin_b12_mcg: food.vitamin_b12_mcg || 0,
  vitamin_b12_rich: food.vitamin_b12_rich || false,
  niacin_mg: food.niacin_mg || 0,
  niacin_rich: food.niacin_rich || false,
  folate_mcg: food.folate_mcg || 0,
  folate_rich: food.folate_rich || false,
  pantothenic_acid_mg: food.pantothenic_acid_mg || 0,
  pantothenic_acid_rich: food.pantothenic_acid_rich || false,
  is_system: food.is_system || true,
  created_at: '2024-01-01T00:00:00Z',
  updated_at: '2024-01-01T00:00:00Z'
}))

// 生成foods.ts内容
const foodsContent = `import { defineStore } from 'pinia'
import type { Food } from '@/types'

// 模拟数据，用于开发测试 - 使用food_data.json中的数据
const mockFoods: Partial<Food>[] = [
${convertedFoods.map(food => `  {
    id: ${food.id},
    name_zh: '${food.name_zh}',
    name_en: '${food.name_en}',
    energy_kcal: ${food.energy_kcal},
    energy_rich: ${food.energy_rich},
    protein_g: ${food.protein_g},
    protein_rich: ${food.protein_rich},
    fat_g: ${food.fat_g},
    fat_rich: ${food.fat_rich},
    carb_g: ${food.carb_g},
    carb_rich: ${food.carb_rich},
    fiber_g: ${food.fiber_g},
    fiber_rich: ${food.fiber_rich},
    cholesterol_mg: ${food.cholesterol_mg},
    cholesterol_rich: ${food.cholesterol_rich},
    sodium_mg: ${food.sodium_mg},
    sodium_rich: ${food.sodium_rich},
    calcium_mg: ${food.calcium_mg},
    calcium_rich: ${food.calcium_rich},
    phosphorus_mg: ${food.phosphorus_mg},
    phosphorus_rich: ${food.phosphorus_rich},
    potassium_mg: ${food.potassium_mg},
    potassium_rich: ${food.potassium_rich},
    iron_mg: ${food.iron_mg},
    iron_rich: ${food.iron_rich},
    vitamin_a_ug: ${food.vitamin_a_ug},
    vitamin_a_rich: ${food.vitamin_a_rich},
    vitamin_c_mg: ${food.vitamin_c_mg},
    vitamin_c_rich: ${food.vitamin_c_rich},
    vitamin_d_mcg: ${food.vitamin_d_mcg},
    vitamin_d_rich: ${food.vitamin_d_rich},
    vitamin_e_mg: ${food.vitamin_e_mg},
    vitamin_e_rich: ${food.vitamin_e_rich},
    thiamin_mg: ${food.thiamin_mg},
    thiamin_rich: ${food.thiamin_rich},
    riboflavin_mg: ${food.riboflavin_mg},
    riboflavin_rich: ${food.riboflavin_rich},
    vitamin_b6_mg: ${food.vitamin_b6_mg},
    vitamin_b6_rich: ${food.vitamin_b6_rich},
    vitamin_b12_mcg: ${food.vitamin_b12_mcg},
    vitamin_b12_rich: ${food.vitamin_b12_rich},
    niacin_mg: ${food.niacin_mg},
    niacin_rich: ${food.niacin_rich},
    folate_mcg: ${food.folate_mcg},
    folate_rich: ${food.folate_rich},
    pantothenic_acid_mg: ${food.pantothenic_acid_mg},
    pantothenic_acid_rich: ${food.pantothenic_acid_rich},
    is_system: ${food.is_system},
    created_at: '${food.created_at}',
    updated_at: '${food.updated_at}'
  }`).join(',\n')}
]

export const useFoodsStore = defineStore('foods', {
  state: () => ({
    foods: mockFoods as Partial<Food>[],
    loading: false,
    error: null as string | null
  }),

  getters: {
    getFoodById: (state) => (id: number) => {
      return state.foods.find(food => food.id === id)
    },
    
    searchFoods: (state) => (query: string) => {
      if (!query) return state.foods
      const lowerQuery = query.toLowerCase()
      return state.foods.filter(food => 
        food.name_zh?.toLowerCase().includes(lowerQuery) ||
        food.name_en?.toLowerCase().includes(lowerQuery)
      )
    }
  },

  actions: {
    async fetchFoods() {
      this.loading = true
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 100))
        // 在实际应用中，这里会调用API
        // this.foods = await api.getFoods()
        this.error = null
      } catch (error) {
        this.error = error instanceof Error ? error.message : 'Unknown error'
        throw error
      } finally {
        this.loading = false
      }
    },

    async addFood(food: Omit<Food, 'id' | 'created_at' | 'updated_at'>) {
      const newFood: Partial<Food> = {
        ...food,
        id: Math.max(...this.foods.map(f => f.id || 0)) + 1,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      }
      this.foods.push(newFood)
      return newFood
    },

    async updateFood(id: number, updates: Partial<Food>) {
      const index = this.foods.findIndex(food => food.id === id)
      if (index !== -1) {
        this.foods[index] = {
          ...this.foods[index],
          ...updates,
          updated_at: new Date().toISOString()
        }
        return this.foods[index]
      }
      throw new Error('Food not found')
    },

    async deleteFood(id: number) {
      const index = this.foods.findIndex(food => food.id === id)
      if (index !== -1) {
        this.foods.splice(index, 1)
        return true
      }
      throw new Error('Food not found')
    }
  }
})
`

// 写入foods.ts文件
const foodsPath = path.join(__dirname, '../src/stores/foods.ts')
fs.writeFileSync(foodsPath, foodsContent)

console.log(`已更新 foods.ts，包含 ${convertedFoods.length} 个食物`)
console.log('食物列表:')
convertedFoods.forEach((food, index) => {
  console.log(`${index + 1}. ${food.name_zh} (${food.name_en})`)
})
